package com.supermarket.controller;

import cn.hutool.core.util.StrUtil;
import com.supermarket.common.ResponseResult;
import com.supermarket.entity.User;
import com.supermarket.entity.Rider;
import com.supermarket.exception.UserException;
import com.supermarket.service.LoginLogService;
import com.supermarket.service.UserService;
import com.supermarket.service.RiderService;
import com.supermarket.service.OrderService;
import com.supermarket.service.CommodityService;
import com.supermarket.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

@RestController
public class CommonController {
    @Resource
    private UserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private RiderService riderService;
    @Resource
    private OrderService orderService;
    @Resource
    private CommodityService commodityService;
    @Resource
    private JwtUtil jwtUtil;
    
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> Login(@RequestBody User user, HttpServletRequest request, HttpSession session) {
        try {
            User loggedInUser = userService.Login(user);
            
            // 生成JWT token
            String token = jwtUtil.generateToken(loggedInUser.getId(), loggedInUser.getRole());
            
            // 记录登录日志
            loginLogService.addLoginLog(loggedInUser.getId(), request.getRemoteAddr(),"SUCCESS");
            
            // 将用户信息存入session（保留此功能，以便后台管理系统继续使用）
            session.setAttribute("currentUser", loggedInUser);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            
            // 复制用户信息，但不包含敏感信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", loggedInUser.getId());
            userInfo.put("username", loggedInUser.getUsername());
            userInfo.put("nickname", loggedInUser.getNickname());
            userInfo.put("role", loggedInUser.getRole());
            userInfo.put("avatar", loggedInUser.getAvatar());
            userInfo.put("email", loggedInUser.getEmail());
            userInfo.put("score", loggedInUser.getScore());
            
            // 添加调试日志
            System.out.println("用户登录成功 - 用户ID: " + loggedInUser.getId());
            System.out.println("用户头像路径: " + loggedInUser.getAvatar());
            
            result.put("userInfo", userInfo);
            
            return ResponseResult.success(result);
        } catch (UserException e) {
            if (e.getUserId() != 0) {
                loginLogService.addLoginLog(e.getUserId(), request.getRemoteAddr(),"FAILED");
            }
            return ResponseResult.error(400, e.getMessage());
        }
    }

    @PostMapping("/logout")
    public ResponseResult<String> Loginout(@RequestBody User user, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return ResponseResult.success("Loginout: null");
        }
        session.setAttribute("currentUser", null);
        return ResponseResult.success("Loginout: "+currentUser.toString());
    }

    // @GetMapping("/getUserVersion")
    // public ResponseResult<Integer> getUserVersion(@RequestBody User user) {
    //     Integer version = userService.getUserById(user.getId()).getVersion();
    //     if (version == null) {
    //         return ResponseResult.error(400, "用户不存在");
    //     }
    //     return ResponseResult.success(version);
    // }

    /**
     * 更新用户信息
     *
     * @param user 用户对象
     * @return 包含操作结果的响应结果
     */
    @PutMapping("/update")
    public ResponseResult<String> updateUser(@RequestBody User user, HttpSession session) {
//        System.out.println((User)session.getAttribute("currentUser"));
//        System.out.println(user);
        // 新增登录验证
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return ResponseResult.error(400, "请先登录");
        }
        
        // 新增权限验证：只能修改自己的账号
        if(!user.getId().equals(currentUser.getId())){
            return ResponseResult.error(400, "不能修改非自身账户");
        }
//        user.setId(currentUser.getId()); // 强制使用当前用户ID
        
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getNickname())){
            return ResponseResult.error(400, "账号或昵称不能为空");
        }
        try {
            int result = userService.updateUser(user);
            if (result > 0) {
                return ResponseResult.success("用户更新成功");
            } else {
                return ResponseResult.error(400, "用户更新失败");
            }
        } catch (RuntimeException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseResult<Map<String, Object>> register(@RequestBody User user) {
        try {
            userService.addUser(user);
            
            Map<String, Object> result = new HashMap<>();
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            result.put("role", user.getRole());
            
            // 如果是骑手角色，返回骑手信息
            if ("RIDER".equals(user.getRole())) {
                Rider rider = riderService.getRiderByUserId(user.getId());
                if (rider != null) {
                    result.put("riderId", rider.getId());
                    result.put("riderStatus", rider.getStatus());
                }
                result.put("message", "骑手注册成功");
                return ResponseResult.success(result);
            }
            
            result.put("message", "用户注册成功");
            return ResponseResult.success(result);
        } catch (UserException e) {
            return ResponseResult.error(400, e.getMessage());
        } catch (Exception e) {
            return ResponseResult.error(500, "注册过程中发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 获取系统统计数据
     * 
     * @return 包含统计数据的响应结果
     */
    @GetMapping("/stats")
    public ResponseResult<Map<String, Object>> getSystemStats() {
        try {
            // 获取统计数据
            int userCount = userService.countUsers();
            int commodityCount = commodityService.countCommodities();
            int riderCount = riderService.countRiders();
            int orderCount = orderService.countOrders();
            
            // 组装统计数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("userCount", userCount);
            stats.put("commodityCount", commodityCount);
            stats.put("riderCount", riderCount);
            stats.put("orderCount", orderCount);
            
            return ResponseResult.success(stats);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取系统统计数据失败: " + e.getMessage());
        }
    }

    
    /**
     * 获取最近14天订单数量统计
     * 
     * @return 包含最近14天每天订单数量的响应结果
     */
    @GetMapping("/order/stats/recent")
    public ResponseResult<Map<String, Object>> getRecentOrderStats() {
        try {
            // 获取最近14天的日期
            List<String> dateList = new ArrayList<>();
            List<Integer> countList = new ArrayList<>();
            
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            
            // 获取最近14天的日期和对应的订单数量
            for (int i = 13; i >= 0; i--) {
                LocalDate date = today.minusDays(i);
                String dateStr = date.format(formatter);
                dateList.add(dateStr);
                
                // 获取当天订单数量
                int count = orderService.countOrdersByDate(dateStr);
                countList.add(count);
            }
            
            // 组装数据
            Map<String, Object> result = new HashMap<>();
            result.put("dates", dateList);
            result.put("counts", countList);
            
            return ResponseResult.success(result);
        } catch (Exception e) {
            return ResponseResult.error(500, "获取最近订单统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类数据
     * 
     * @return 分类数据JSON
     */
    @GetMapping("/category.json")
    public Object getCategoryJson() {
        try {
            // 返回分类数据
            return new Object[] {
                Map.of("name", "特价泡面", "Tag", new String[]{"特价泡面","泡面"}),
                Map.of("name", "特价零食", "Tag", new String[]{"特价零食","零食"}),
                Map.of("name", "特价饮料", "Tag", new String[]{"特价饮料","饮料"}),
                Map.of("name", "炸串小吃", "Tag", new String[]{"炸串小吃","炸串"}),
                Map.of("name", "炒饭盖饭", "Tag", new String[]{"炒饭盖饭","炒饭","盖饭"}),
                Map.of("name", "炸鸡", "Tag", new String[]{"炸鸡"}),
                Map.of("name", "汉堡", "Tag", new String[]{"汉堡"}),
                Map.of("name", "男士专区", "Tag", new String[]{"男士专区","烟","酒","打火机","槟榔"}),
                Map.of("name", "方便速食", "Tag", new String[]{"方便速食","方便面","速食"}),
                Map.of("name", "火腿肠", "Tag", new String[]{"火腿肠"}),
                Map.of("name", "薯片系列", "Tag", new String[]{"薯片","乐事"}),
                Map.of("name", "辣条", "Tag", new String[]{"辣条"}),
                Map.of("name", "瓜子系列", "Tag", new String[]{"瓜子"}),
                Map.of("name", "干脆面", "Tag", new String[]{"干脆面"}),
                Map.of("name", "酒水饮料", "Tag", new String[]{"酒水饮料","饮料","酒","饮品"}),
                Map.of("name", "休闲零食", "Tag", new String[]{"休闲零食","零食","休闲","小吃"}),
                Map.of("name", "面包蛋糕", "Tag", new String[]{"面包","蛋糕"}),
                Map.of("name", "饼干食品", "Tag", new String[]{"饼干"}),
                Map.of("name", "生活日用", "Tag", new String[]{"纸巾","笔","学习用品","垃圾袋"}),
                Map.of("name", "矿泉水", "Tag", new String[]{"矿泉水","水","饮用水"})
            };
        } catch (Exception e) {
            System.out.println("获取分类数据失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseResult.error(500, "获取分类数据失败: " + e.getMessage());
        }
    }
}
